﻿using System;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace InfoPathExtractionRules
{
    public class ExtractPostBackCanary : ExtractionRule
    {
        /// <summary>
        /// When interacting with an InfoPath form in the browser, it may postback to refresh data
        /// A canary value is required for subsequent postbacks to the server
        /// The canary value is set in a javascript array
        /// We are trying to extract that value from the javascript array
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Extract(object sender, ExtractionEventArgs e)
        {
            string var = IPExtractionUtil.getg_ObjCurrentFormData(e.Response.BodyString);
            e.Success = true;
            if (string.IsNullOrEmpty(var))
            {
                e.Message = "Could not find g_ObjCurrentFormData";
                e.Success = false;
                return;
            }

            int index = (int)IPExtractionUtil.CurrentFormData.CanaryValue;
            string postBackCanary = IPExtractionUtil.extractItemFromJavascriptArray(var, index);

            // HACK
            // If we couldn't find the canary, we could be on an RTM version of the server
            // which means the canary is at a different index
            if (postBackCanary == null)
            {
                index = (int)IPExtractionUtil.CurrentFormDataRTM.CanaryValue;
                postBackCanary = IPExtractionUtil.extractItemFromJavascriptArray(var, index);
            }


            if (string.IsNullOrEmpty(postBackCanary))
            {
                e.Message = "Could not find postBackCanary";
                e.Success = false;
                return;
            }

            postBackCanary = postBackCanary.Trim('"');
            postBackCanary = Regex.Unescape(postBackCanary);

            e.WebTest.Context[this.ContextParameterName] = postBackCanary;
        }

        public override string RuleName
        {
            get { return "ExtractPostBackCanary"; }
        }
    }
}
